﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
using Microsoft.Win32.SafeHandles;
using System.Windows.Interop;
using System.IO;

namespace EveruWPF.Windows.Helpers
{
    public class CursorHelper
    {
        private struct IconInfo
        {
            public bool fIcon;
            public int xHotspot;
            public int yHotspot;
            public IntPtr hbmMask;
            public IntPtr hbmColor;
        }

        [DllImport("user32.dll")]
        private static extern IntPtr CreateIconIndirect(ref IconInfo icon);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);


        /// <summary>
        /// Returns a Cursor with Hotspots
        /// </summary>
        /// <param name="ImageStream">Stream og Cursorimage</param>
        /// <param name="xHotSpot">X Hotspot</param>
        /// <param name="yHotSpot">Y Hotspot</param>
        /// <returns>A Cursor</returns>
        public static System.Windows.Input.Cursor CreateCursor(Stream ImageStream, int xHotSpot, int yHotSpot)
        {
            Bitmap bmp = new Bitmap(ImageStream);

            IconInfo tmp = new IconInfo();
            GetIconInfo(bmp.GetHicon(), ref tmp);
            tmp.xHotspot = xHotSpot;
            tmp.yHotspot = yHotSpot;
            tmp.fIcon = false;

            IntPtr ptr = CreateIconIndirect(ref tmp);
            SafeFileHandle handle = new SafeFileHandle(ptr, true);
            return CursorInteropHelper.Create(handle);
        }

    }
}
